<template>
  <van-cell-group>
    <van-field class="van-cell--center" type="password" placeholder="请输入原交易密码" name="old_safe_password" required
      label="原交易密码" v-model="formFields.old_safe_password"
      :error="$validator.errors.has('old_safe_password')" :error-message="$validator.errors.first('old_safe_password')"
      data-vv-as="原交易密码" v-validate="{required: true, min: 6}"
    />

    <van-field class="van-cell--center" type="password" placeholder="请输入新交易密码" name="safe_password" required
      label="新交易密码" v-model="formFields.safe_password"
      :error="$validator.errors.has('safe_password')" :error-message="$validator.errors.first('safe_password')"
      data-vv-as="新交易密码" v-validate="{required: true, min: 6}"
    />

    <van-field class="van-cell--center" type="password" placeholder="请输入登陆密码" name="login_password" required
      label="登陆密码" v-model="formFields.login_password"
      :error="$validator.errors.has('login_password')" :error-message="$validator.errors.first('login_password')"
      data-vv-as="登陆密码" v-validate="{required: true, min: 6}"
    />

    <van-button type="primary" :loading="onButtonLoading" @click="onSubmit" style="width: 100%;">提交</van-button>
  </van-cell-group>
</template>

<script>
  import qs from 'qs';
  import { Button, Cell, CellGroup, Field, Toast } from 'vant';
  import userApi from '@/api/user/index';

  export default {
    components: {
      [Button.name]: Button,
      [Cell.name]: Cell,
      [CellGroup.name]: CellGroup,
      [Field.name]: Field
    },
    data() {
      return {
        onButtonLoading: false,
        formFields: {
          old_safe_password: '',
          safe_password: '',
          login_password: ''
        }
      }
    },
    methods: {
      onSubmit() {
        this.onButtonLoading = true;

        this.$validator.validateAll().then((isValid) => {
          if(isValid) {
            userApi.updateSafePasswordByToken(this.formFields).then((data) => {
              Toast(data.msg);
              if(parseInt(data.code) === 0) {
                setTimeout(() => {
                  this.$router.push({name: 'userIndex'});
                }, 1500);
                return true;
              }
              this.onButtonLoading = false;
            });
          } else {
            Toast('请输入必要栏目');
            this.onButtonLoading = false;
          }

          return;
        });
      }
    }
  }
</script>
